package com.titaniume.java;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 *@program: java8
 *@description: Java8 四大内置函数式接口
 *
 *  Consumer<T> : 消费型接口
 *    void accept(T t);
 *
 *  Supplier<T>: 供给型接口
 *     T get();
 *
 *   Function<T,R>: 函数型接口
 *      R apply(T t);
 *
 *   Predicate<T> :断言型接口
 *     boolean test(T t);
 *
 *
 *
 *
 *@author: renfei.huang
 *@create: 2021-10-28 15:54
 */
public class TestLambda3 {




    // Predicate<T> :断言型接口
    @Test
    public void test4(){
        List<String> list = Arrays.asList("erqwrqw", "gg", "111", "erwe");
        List<String> strList = filterStr(list, (s) -> s.length() > 3);
        for (String s :strList){
            System.out.println(s);
        }
    }

    //需求：将满足条件的字符串，放入集合中
    public  List<String> filterStr(List<String> list, Predicate<String> predicate){
        List<String> strList = new ArrayList<>();
        for (String str:list){
            if(predicate.test(str)){
                strList.add(str);
            }
        }
        return  strList;
    }





    //Function<T,R>: 函数型接口
    @Test
    public void test3(){
        System.out.println(strHandler("\t\t\t\t一心一意的工作\t\t\t", (str) -> str.trim()));
        System.out.println(strHandler("我爱我的祖国", (str) -> str.substring(4, 6)));
    }
    //需求： 用于处理字符串
    public  String strHandler(String str, Function<String,String> function){
        return  function.apply(str);
    }


    //Supplier<T>: 供给型接口
    @Test
    public void test2(){
        List<Integer> numList = getNumList(20, () -> (int) (Math.random() * 100));
        for (Integer num : numList) {
            System.out.println(num);
        }
    }

    //需求：产生指定个数的整数，并放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> supplier){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num ; i++) {
            Integer n = supplier.get();
            list.add(n);
        }
        return  list;
    }





    //Consumer<T> : 消费型接口
    @Test
    public void test1(){

        happy(1000,(m) -> System.out.println("xxx喜欢大宝剑,每次消费"+ m +"元"));
    }

    public  void happy(double money, Consumer<Double> consumer){
        consumer.accept(money);
    }
}
